<template>
  <el-row :gutter="24">
    <el-col :span="4">
      <recordTypeTree @type-tree-click="treeNodeClick" @clear-select="clearSelect"></recordTypeTree>
    </el-col>

    <!-- =======================列表搜索模块================= -->
    <el-col :span="20">
      <div class="mod-config">
        <el-form
          :inline="true"
          :model="dataForm"
          @keyup.enter.native="getDataList()"
        >
          <el-form-item>
            <el-input
              v-model="dataForm.key"
              placeholder="参数名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="getDataList()"
              >查询</el-button
            >
            <el-button
              type="success"
              icon="el-icon-plus"
              v-if="isAuth('product:brand:save')"
              @click="addCardHandle()"
              >新增</el-button
            >
          </el-form-item>
        </el-form>

      <!-- =======================列表内容================= -->
        <el-row>
          <el-col :span="6" v-for="card in dataList" :key="card.id">
            <el-card class="box-card" style="margin-top: 15px">
              <div slot="header" class="clearfix">
                <span style="bottom: 7px; position: relative">{{
                  card.cardName
                }}</span>

                <span @click="switchCard(card.id)">
                  <icon-svg
                    style="width: 22px; height: 22px; margin-left: 4px"
                    name="change01"
                  ></icon-svg>
                </span>

                <el-dropdown
                  @command="operateHandle"
                  style="float: right; padding: 2px 0; margin-left: 4px"
                >
                  <span class="el-dropdown-link">
                    操作<i class="el-icon-arrow-down el-icon--right"></i>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      :command="beforeOperateHandle(card.id, 'add')"
                      >新增</el-dropdown-item
                    >
                    <el-dropdown-item>修改</el-dropdown-item>
                    <el-dropdown-item
                      :command="beforeOperateHandle(card.id, 'del')"
                      >删除</el-dropdown-item
                    >
                    <el-dropdown-item>置顶</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>

              <div>
                <el-carousel
                  indicator-position="none"
                  :autoplay="false"
                  :ref="'cardCarousel' + card.id"
                >
                  <el-carousel-item
                    v-for="(chunk, index) in card.recordChunk"
                    :key="index"
                  >
                    <div
                      v-for="record in chunk"
                      :key="record.id"
                      class="text item"
                    >
                      <div style="margin-top: 5px">
                        <span class="word">{{ record.word }}</span>
                        <span class="word-type">{{ record.wordClass }}</span>
                        <span style="margin-left: 2px">{{
                          record.wordDts
                        }}</span>
                      </div>
                    </div>
                  </el-carousel-item>
                </el-carousel>
              </div>
            </el-card>
          </el-col>
        </el-row>

         <!-- =======================卡片新增================= -->
        <el-row>
          <el-col :span="12" :offset="2">
            <el-pagination
              @current-change="changes"
              background
              layout="prev, pager, next"
              :total="1000"
              style="margin: 20px"
            >
            </el-pagination>
          </el-col>
        </el-row>

        <!-- =======================卡片新增================= -->
        <el-dialog
          title="新增卡片"
          :visible.sync="addCardVisible"
          width="25%"
          label-width="80px"
        >
          <el-form :model="cardFrom" ref="cardFrom" label-width="80px">
            <el-form-item label="分类" prop="recordType">
              <recordTypeCascader
                :paths.sync="cardFrom.paths"
              ></recordTypeCascader>
            </el-form-item>

            <el-form-item label="名称" prop="cardName">
              <el-input
                v-model="cardFrom.cardName"
                placeholder="名称"
              ></el-input>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="addCardVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitCardData">确 定</el-button>
          </span>
        </el-dialog>

        <!-- =======================单词记录新增================= -->
        <el-dialog
          title="新增记录"
          :visible.sync="addWordRecordVisible"
          width="25%"
          label-width="80px"
        >
          <el-form :model="recordFrom" ref="recordFrom" label-width="80px">
            <el-form-item label="单词" prop="attrGroupName">
              <el-input v-model="recordFrom.word" placeholder="单词"></el-input>
            </el-form-item>

            <el-form-item label="分类" prop="attrGroupName">
              <el-radio-group v-model="recordFrom.wordClass" size="small">
                <el-radio label="adj." border>adj</el-radio>
                <el-radio label="n." border>n</el-radio>
                <el-radio label="v." border>v</el-radio>
                <!-- phrase 短语 -->
                <el-radio label="ph." border>短语</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="释义" prop="attrGroupName">
              <el-input
                v-model="recordFrom.wordDts"
                placeholder="释义"
              ></el-input>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="addWordRecordVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitRecordData"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </div>
    </el-col>
  </el-row>
</template>

<script>
import recordTypeCascader from "./recordtype-cascader";
import recordTypeTree from "./recordtype-tree";

import chunk from "lodash/chunk"; // https://www.lodashjs.com/docs/lodash.chunk

export default {
  data() {
    return {
      //卡片信息
      cardFrom: {
        id: "",
        paths: [],
        cardName: "",
        recordList: [],
        recordChunk: [], //分页数组
      },
      addWordRecordVisible: false, //新增单词记录
      addCardVisible: false, //新增模块
      dataForm: {
        cardId: 0
      },
      //单词记录
      recordFrom: {
        word: "",
        wordDts: "",
        cardId: 0,
        wordClass: "",
      },
      //卡片列表
      dataList: [],
      typePath: []
    };
  },
  components: {
    recordTypeCascader,
    recordTypeTree,
  },
  activated() {
    this.getDataList();
  },
  methods: {
    getDataList() {
      this.$http({
        url: this.$http.adornUrl("/product/word/word-card/list"),
        method: "get",
        params: this.$http.adornParams({
          key: this.dataForm.key,
          ... (this.dataForm.cardId !== 0 && {cardId: this.dataForm.cardId})
        }),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          let list = data.page.list;
          this.dataList = list;

          this.dataList.forEach((card) => {
            let cList = chunk(card.recordList, 4);
            card.recordChunk = cList;
          })
          this.delCarouselMouse();
        } else {
          this.dataList = [];
        }
      });
    },
    //禁用走马灯组件的鼠标悬浮事件
    delCarouselMouse() {
      //https://blog.csdn.net/weixin_52534121/article/details/126509088 参考
      this.$nextTick(function () {
        // 仅在整个视图都被渲染之后才会运行的代码
        this.dataList.forEach((card) => {
          this.$refs["cardCarousel" + card.id][0].handleMouseEnter = () => {};
        });
      });
    },
    //新增卡片名称
    submitCardData() {
      this.$http({
        url: this.$http.adornUrl(
          `/product//word/word-card/${!this.cardFrom.id ? "save" : "update"}`
        ),
        method: "post",
        data: this.$http.adornData({
          id: this.cardFrom.id || undefined,
          cardName: this.cardFrom.cardName,
          recordType: this.parentCid,
          isTop: 0,
        }),
      }).then(({ data }) => {
        this.addCardVisible = false;
        this.$modal.msgSuccess("操作成功");
        this.getDataList();
      });
    },
    //新增单词记录
    submitRecordData() {
      console.log("car from ",this.recordFrom);
      let { word, wordDts, cardId, wordClass } = this.recordFrom;
      
      this.$http({
        url: this.$http.adornUrl(`/product/word/word-record/save`),
        method: "post",
        data: this.$http.adornData( { word, wordDts, cardId, wordClass }),
      }).then(({ data }) => {
        this.addWordRecordVisible = false;
        this.$modal.msgSuccess("操作成功");
        this.getDataList();
      });
    },
    //操作按钮回调
    operateHandle(param) {
      this.$nextTick(() => {
        this.$refs["recordFrom"].resetFields();
        this.recordFrom.cardId = param.cardId;
        console.log("重置后的表单: ",this.$refs["recordFrom"] );
        
      });
      
      if (param.command === "add"){
        this.addWordRecordVisible = true; //打开窗口
      } 

      if (param.command === "del") this.delRecordHandle();
    },
    //操作按钮 - 获取参数
    beforeOperateHandle(cardId, command) {
      return { cardId, command };
    },
    //删除卡片处理
    delRecordHandle() {
      this.$confirm("是否删除卡片", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl(`/product/word/word-card/delete`),
          method: "delete",
          data: this.$http.adornData([this.recordFrom.cardId], false),
        }).then(({ data }) => {
          this.addWordRecordVisible = false;
          this.$modal.msgSuccess("操作成功");
          this.getDataList();
        });
      });
    },
    switchCard(cardId) {
      this.$refs["cardCarousel" + cardId][0].next(); //调用组件内置方法
    },
    //卡片新增按钮回调
    addCardHandle() {
      this.addCardVisible = true;
      this.$nextTick(() => {
        this.$refs["cardFrom"].resetFields();
        this.cardFrom.paths = this.typePath;
      });
    },
    changes() {
      console.log("分页修改");
    },
    //感知树节点被点击
    treeNodeClick(data,node){
      console.log("树节点被点击02:",data , node);
      
      // //只处理最后一级级分类的
      if(!node.isLeaf){
        return;
      }
      this.typePath = this.getTypePth(node);
      this.dataForm.cardId = data.id;
      this.getDataList();
    },
    //清除选中节点
    clearSelect(){
      this.typePath = [];
      this.dataForm.cardId = 0;
      this.getDataList();
    },
    //获取类型中选中的路径
    getTypePth(node){
      
      let path = [];
      let next = node;
      do{
        if(next.data.id) {
          path.unshift(next.data.id);
        }
        
        next = next.parent;
      }while(next);

      //console.log("path 002 :" ,path );
      return path;
    }
  },
  //生命周期函数 在实例创建完成后被立即同步调用。
  created() {},
  computed: {
    parentCid() {
      //pop() 方法用于从数组中删除并返回最后一个元素。
      let pid = this.cardFrom.paths.slice(-1)[0];
      return pid;
    },
  },
};
</script>

<style>
.box-card {
  width: 300px;
}

.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}

.word-type {
  color: #999;
  display: inline-block;
  padding-right: 4px;
  vertical-align: top;
  white-space: nowrap;
  margin-left: 2px;
  width: 28px;
}

.word {
  font-weight: bold;
  display: inline-block;
  width: 83px;
}

.el-card__body {
  /* overflow-y: auto; 显示垂直滚动条 */
  padding: 10px;
  /* height: 250px; */
}

.el-card__header {
  padding: 10px 10px;
}
</style>